package com.huajx.core.handler;

import org.apache.mina.core.future.IoFutureListener;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

import com.huajx.core.model.HttpRequestMessage;
import com.huajx.core.model.HttpResponseMessage;

public class ServerHandler extends IoHandlerAdapter {
    private HttpHandler handler;

    public HttpHandler getHandler() {
        return handler;
    }

    public void setHandler(HttpHandler handler) {
        this.handler = handler;
    }

    @Override
    public void sessionOpened(IoSession session) {
        // set idle time to 60 seconds
        session.getConfig().setIdleTime(IdleStatus.BOTH_IDLE, 60);
    }

    @Override
    public void messageReceived(IoSession session, Object message) {
        // Check that we can service the request context
        HttpRequestMessage request = (HttpRequestMessage) message;
        HttpResponseMessage response = handler.handle(request);
        if (response != null) {
            session.write(response).addListener(IoFutureListener.CLOSE);
        }
    }

    @Override
    public void sessionIdle(IoSession session, IdleStatus status) {
        session.closeOnFlush();
    }

    @Override
    public void exceptionCaught(IoSession session, Throwable cause) {
        session.closeOnFlush();
    }
}
